<template>
  <div class="dashboard">
    <h1 class="page-title">仪表盘</h1>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card" style="background: linear-gradient(135deg, #667eea, #764ba2)">
          <div class="stat-icon">
            <el-icon :size="40"><Document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ overview.todayLogCount || 0 }}</div>
            <div class="stat-label">今日日志总数</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card" style="background: linear-gradient(135deg, #f093fb, #f5576c)">
          <div class="stat-icon">
            <el-icon :size="40"><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ overview.todayErrorCount || 0 }}</div>
            <div class="stat-label">今日错误日志</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card" style="background: linear-gradient(135deg, #4facfe, #00f2fe)">
          <div class="stat-icon">
            <el-icon :size="40"><Bell /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ overview.unhandledAlarmCount || 0 }}</div>
            <div class="stat-label">未处理告警</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card" style="background: linear-gradient(135deg, #43e97b, #38f9d7)">
          <div class="stat-icon">
            <el-icon :size="40"><Connection /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ overview.activeSourceCount || 0 }}/{{ overview.totalSourceCount || 0 }}</div>
            <div class="stat-label">活跃采集源</div>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :md="16">
        <div class="card">
          <div class="card-header">
            <h3>日志量趋势</h3>
          </div>
          <v-chart :option="logTrendOption" style="height: 350px" autoresize />
        </div>
      </el-col>
      
      <el-col :xs="24" :md="8">
        <div class="card">
          <div class="card-header">
            <h3>日志级别分布</h3>
          </div>
          <v-chart :option="levelPieOption" style="height: 350px" autoresize />
        </div>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :xs="24" :md="12">
        <div class="card">
          <div class="card-header">
            <h3>系统日志分布</h3>
          </div>
          <v-chart :option="systemBarOption" style="height: 300px" autoresize />
        </div>
      </el-col>
      
      <el-col :xs="24" :md="12">
        <div class="card">
          <div class="card-header">
            <h3>最近告警</h3>
          </div>
          <div class="alarm-list">
            <div v-for="alarm in recentAlarms" :key="alarm.id" class="alarm-item">
              <div class="alarm-icon">
                <el-icon :size="24" color="#f56c6c"><Bell /></el-icon>
              </div>
              <div class="alarm-content">
                <div class="alarm-title">{{ alarm.ruleName }}</div>
                <div class="alarm-time">{{ alarm.alarmTime }}</div>
              </div>
              <el-tag :type="alarm.status === 0 ? 'danger' : 'success'">
                {{ alarm.status === 0 ? '未处理' : '已处理' }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getDashboardOverview, getStatistics } from '@/api/dashboard'
import { getUnhandledAlarms } from '@/api/alarm'

const overview = ref({})
const recentAlarms = ref([])

// 日志趋势图配置
const logTrendOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '日志量',
      type: 'line',
      data: [],
      smooth: true,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ]
        }
      },
      itemStyle: {
        color: '#409eff'
      }
    }
  ]
})

// 级别分布饼图配置
const levelPieOption = reactive({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center'
  },
  series: [
    {
      name: '日志级别',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
})

// 系统分布柱状图配置
const systemBarOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '日志量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: '#409eff' },
            { offset: 1, color: '#66b1ff' }
          ]
        },
        borderRadius: [10, 10, 0, 0]
      }
    }
  ]
})

// 加载Dashboard数据
const loadDashboard = async () => {
  try {
    const res = await getDashboardOverview()
    if (res.code === 200) {
      overview.value = res.data
      
      // 更新日志趋势图
      if (res.data.last24HoursLogTrend) {
        logTrendOption.xAxis.data = res.data.last24HoursLogTrend.map(item => item.time)
        logTrendOption.series[0].data = res.data.last24HoursLogTrend.map(item => item.count)
      }
    }
    
    // 加载统计数据（获取日志级别分布和系统分布）
    const statsRes = await getStatistics(7)  // 获取近7天统计
    if (statsRes.code === 200 && statsRes.data) {
      const data = statsRes.data
      
      // 更新日志级别分布饼图
      if (data.logLevelDistribution && data.logLevelDistribution.length > 0) {
        levelPieOption.series[0].data = data.logLevelDistribution.map(item => ({
          name: item.logLevel || item.log_level || 'UNKNOWN',
          value: item.count || 0
        }))
      }
      
      // 更新系统分布柱状图
      if (data.systemTypeDistribution && data.systemTypeDistribution.length > 0) {
        systemBarOption.xAxis.data = data.systemTypeDistribution.map(item => 
          item.systemType || item.system_type || 'UNKNOWN'
        )
        systemBarOption.series[0].data = data.systemTypeDistribution.map(item => 
          item.count || 0
        )
      }
    }
  } catch (error) {
    console.error('加载Dashboard数据失败', error)
  }
}

// 加载告警数据
const loadAlarms = async () => {
  try {
    const res = await getUnhandledAlarms()
    if (res.code === 200) {
      recentAlarms.value = res.data.slice(0, 5) // 只显示最近5条
    }
  } catch (error) {
    console.error('加载告警数据失败', error)
  }
}

onMounted(() => {
  loadDashboard()
  loadAlarms()
})
</script>

<style scoped lang="scss">
.dashboard {
  .stat-cards {
    margin-bottom: 20px;
    
    .stat-card {
      border-radius: 16px;
      padding: 24px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
      }
      
      .stat-icon {
        opacity: 0.8;
      }
      
      .stat-info {
        text-align: right;
        
        .stat-value {
          font-size: 32px;
          font-weight: bold;
          margin-bottom: 8px;
        }
        
        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }
      }
    }
  }
  
  .charts-row {
    margin-bottom: 20px;
  }
  
  .card-header {
    margin-bottom: 20px;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
    }
  }
  
  .alarm-list {
    max-height: 300px;
    overflow-y: auto;
    
    .alarm-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid var(--border-color);
      transition: all 0.2s ease;
      
      &:hover {
        background-color: var(--el-fill-color-light);
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      .alarm-icon {
        margin-right: 16px;
      }
      
      .alarm-content {
        flex: 1;
        
        .alarm-title {
          font-size: 14px;
          font-weight: 500;
          color: var(--text-primary);
          margin-bottom: 4px;
        }
        
        .alarm-time {
          font-size: 12px;
          color: var(--text-secondary);
        }
      }
    }
  }
}
</style>

